'use strict'

import {app, BrowserWindow, globalShortcut, ipcMain, Menu, Notification, screen, shell, Tray, powerMonitor} from 'electron'

const path = require('path')
const os = require("os");
const isWin7 = os.release().startsWith('6.1')
if (isWin7) app.disableHardwareAcceleration()
const isDevelopment = process.env.ENV == "development"
const {enable} = require('@/common/winUtils/enable');
const file = require('@/common/utils/file')
file.writeProcessTrace()

const config = require('@/common/winUtils/config')
const secretUtil = require('@/common/winUtils/secretUtil');
const checkWin = require('@/common/winUtils/checkWin');
const shopWin = require('@/common/winUtils/shopWin');
const setShopWin = require('@/common/winUtils/setShopWin');
const adWin = require('@/common/winUtils/adWin');

let domain = process.env.VUE_APP_WEB_DOMAIN, win = null, secret = ''
let {ico} = config.getAppConfig()
const gotTheLock = app.requestSingleInstanceLock()
if (!gotTheLock) {
  app.quit()
} else {
  app.on("second-instance", (event, commandLine, workingDirectory) => {
    if (win) {
      toggleWindowVisibility();
    }
  })

  function createWindow(fun = null) {
    let winWidth = 70, winHeight = 150;
    win = new BrowserWindow({
      width: winWidth,
      height: winHeight,
      transparent: true,
      backgroundColor: '#00000000',
      modal: true,
      x: parseInt(screen.getPrimaryDisplay().workAreaSize.width - winWidth),
      y: parseInt((screen.getPrimaryDisplay().workAreaSize.height - winHeight) / 2),
      frame: false,
      icon: ico,
      resizable: false,
      maximizable: false,
      minimizable: false,
      skipTaskbar: true,
      show: false,
      title: "网吧商品超市",
      webPreferences: {
        partition: String(+new Date()),
        plugins: true,
        nodeIntegration: true,
        contextIsolation: false,
        webViewTag: true,
        webSecurity: false,
        enableRemoteModule: true,
        hardwareAcceleration: false,
      }
    })

    win.setMenu(null);
    globalShortcut.register('CommandOrControl+Shift+i', function () {
      win.webContents.openDevTools({mode: 'detach'});
    })

    loadURLBasedOnEnvironment();

    enable(win);
    win.once('closed', () => {
      win = null
    })
    win.once('ready-to-show', () => {
      win.show();
      if (fun) fun()
    });

    // 保留现有的事件处理
    win.on('blur', () => {
      if (win.isMinimized()) win.restore()
    });

    win.on('minimize', (event) => {
      event.preventDefault();
      toggleWindowVisibility();
    });

    ipcMain.on("window-check-show", (event, obj) => {
      checkWin.createWin(secret)
    });
    ipcMain.on("open-web", function (event, url) {
      shell.openExternal(url);
    })
    ipcMain.on('window-notification', function (event, message) {
      new Notification({
        title: '消息通知',
        body: message
      }).show()
    })

    ipcMain.on('quit', () => {
      quitApplication();
    })

    const tray = new Tray(ico);
    tray.setToolTip("网吧超市")
    tray.on("click", () => {
      if (win) {
        toggleWindowVisibility();
      } else {
        createWindow(() => {
          shopWin.createWin(secret)
          adWin.createWin()
        })
      }
    })
  }

  function toggleWindowVisibility() {
    if (win.isMinimized()) win.restore()
    win.focus()
    win.show()
    shopWin.changePage(1)
  }

  function loadURLBasedOnEnvironment() {
    if (isDevelopment) {
      win.loadURL(`${domain}/tab?secret=${secret}`, { extraHeaders: "pragma: no-cache\n" });
    } else {
      win.loadURL(`file://${path.join(__dirname, 'index.html')}#/tab?secret=${secret}`);
    }
  }

  function quitApplication() {
    console.log('应用正在退出');
    checkWin.quit()
    shopWin.quit()
    adWin.closeWin()
    if (win) win.close()
    app.exit()
  }

  app.on("window-all-closed", () => {
    if (process.platform !== "darwin") {
      app.quit()
    }
  })

  app.on("activate", () => {
    if (win === null) {
      createWindow()
    }
  })
  app.on("ready", async () => {
    const fun = (shopId) => {
      secret = secretUtil.get(shopId)
      createWindow(() => {
        shopWin.createWin(secret)
        adWin.createWin()
      })
    }
    file.configRead().then((shopId) => {
      fun(shopId)
    }).catch((err) => {
      setShopWin.createWin((shopId) => {
        fun(shopId)
      })
    })
  })
}
if (process.platform === "win32") {
  process.on("message", (data) => {
    if (data === "graceful-exit" || data === "WM_QUERYENDSESSION") {
      app.quit();
    }
  })
} else {
  process.on("SIGTERM", () => {
    app.quit()
  })
}
